package org.jflame.commons.json.fastjson;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DecimalFormat;

import com.alibaba.fastjson.serializer.BeanContext;
import com.alibaba.fastjson.serializer.BigDecimalCodec;
import com.alibaba.fastjson.serializer.ContextObjectSerializer;
import com.alibaba.fastjson.serializer.JSONSerializer;

/**
 * 自定义BigDecimal json序列化,去掉尾部多余的0
 * 
 * @author charles.zhang
 */
public class BigDecimalStripZeroSerializer extends BigDecimalCodec implements ContextObjectSerializer {

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
            throws IOException {
        BigDecimal val = (BigDecimal) object;
        // 有小数位的去掉尾部0
        int scale = val.scale();
        if (scale > 0) {
            serializer.write(val.stripTrailingZeros()
                    .toPlainString());
            return;
            /*
            val = val.stripTrailingZeros();
            // 0.00000012类似这样的数,前端JS解析JSON会自动变成科学计数,改成字符串输出
            if (scale > 6 && BigDecimal.ONE.compareTo(val) > 0 && pattern.matcher(val.toPlainString())
                    .find()) {
                serializer.write(val.toPlainString());
                return;
            }
            */
        }
        super.write(serializer, val, fieldName, fieldType, features);
    }

    @Override
    public void write(JSONSerializer serializer, Object object, BeanContext context) throws IOException {
        if (object != null && context.getFormat() != null) {
            DecimalFormat fmt = new DecimalFormat(context.getFormat());
            serializer.out.writeString(fmt.format(object));
        }
    }

}
